package com.zhuhjay.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.zhuhjay.mapper.BookMapper;
import com.zhuhjay.mapper.TypeMapper;
import com.zhuhjay.model.dto.BookInsertDto;
import com.zhuhjay.model.dto.BookUpdateDto;
import com.zhuhjay.model.entity.Book;
import com.zhuhjay.model.entity.Type;
import com.zhuhjay.model.vo.BookVo;
import com.zhuhjay.model.vo.PageInfoVo;
import com.zhuhjay.service.BookService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.stream.Collectors;

/**
 * @author ZhuHJay
 * @date 2023/4/26 17:00
 */
@Service
public class BookServiceImpl implements BookService {

    @Resource
    private BookMapper bookMapper;

    @Resource
    private TypeMapper typeMapper;

    @Override
    public PageInfoVo<BookVo> page(Integer num, Integer size) {
        Page<Book> page = bookMapper.paginate(new Page<>(num, size), QueryWrapper.create());
        PageInfoVo<BookVo> pageInfo = new PageInfoVo<>();
        pageInfo.setPageNum(page.getPageNumber());
        pageInfo.setPageSize(page.getPageSize());
        pageInfo.setTotalRow(page.getTotalRow());
        pageInfo.setTotalPage(page.getTotalPage());
        pageInfo.setRecords(page.getRecords().stream().map(book -> {
            BookVo vo = new BookVo();
            BeanUtil.copyProperties(book, vo);
            Type type = typeMapper.selectOneById(book.getTypeid());
            vo.setTypeName(type.getName());
            return vo;
        }).collect(Collectors.toList()));
        return pageInfo;
    }

    @Override
    public void insert(BookInsertDto bookVo) {
        Book book = BeanUtil.copyProperties(bookVo, Book.class);
        book.setPic("");
        bookMapper.insert(book);
    }

    @Override
    public BookVo one(Integer id) {
        Book book = bookMapper.selectOneById(id);
        if (book == null) {
            throw new RuntimeException("书籍不存在");
        }
        BookVo bookVo = BeanUtil.copyProperties(book, BookVo.class);
        Type type = typeMapper.selectOneById(book.getTypeid());
        bookVo.setTypeName(type.getName());
        return bookVo;
    }

    @Override
    public void update(BookUpdateDto bookVo) {
        Book book = bookMapper.selectOneById(bookVo.getId());
        if (book == null) {
            throw new RuntimeException("书籍不存在");
        }
        BeanUtil.copyProperties(bookVo, book);
        bookMapper.update(book);
    }

    @Override
    public void delete(Integer id) {
        Book book = bookMapper.selectOneById(id);
        if (book == null) {
            throw new RuntimeException("书籍不存在");
        }
        bookMapper.deleteById(id);
    }
}
